<template>
  <view class="container">
    <!-- 连接控制区域 -->
    <view class="control-area">
      <button @click="connect" :disabled="connected || isConnecting" type="primary">连接</button>
      <button @click="disconnect" :disabled="!connected" type="warn">断开</button>
      <text class="status">
        {{ connected ? '已连接' : (isConnecting ? '连接中...' : '未连接') }}
      </text>
    </view>

    <!-- 消息发送区域 -->
    <view class="send-area">
      <input v-model="messageToSend" placeholder="输入要发送的消息" class="message-input" />
      <button @click="sendMessage" :disabled="!connected" type="primary">发送</button>
    </view>

    <!-- 消息接收区域 -->
    <view class="message-area">
      <view class="title">接收到的消息</view>
      <scroll-view class="messages" scroll-y="true">
        <view 
          v-for="(msg, index) in receivedMessages" 
          :key="index" 
          class="message-item"
        >
          <text class="timestamp">{{ msg.timestamp }}</text>
          <text class="type">[{{ msg.type }}]</text>
          <text class="content">{{ msg.content }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- 日志区域 -->
    <view class="log-area">
      <view class="title">操作日志</view>
      <scroll-view class="logs" scroll-y="true">
        <view 
          v-for="(log, index) in logs" 
          :key="index" 
          class="log-item"
        >
          {{ log }}
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      logs: [],
      connected: false,
      mqttClient: null,
      messageToSend: '',
      receivedMessages: [],
      isConnecting: false,
      isSubscribed: false,
      useWebSocket: false
    }
  },
  methods: {
    // 连接服务器（兼容三端，mqtt地址与index.vue一致）
    connect() {
      if (this.connected || this.isConnecting) return;
      this.isConnecting = true;
      const self = this;
      self.logs.push('正在连接服务器...');
      try {
        const mqtt = require('mqtt/dist/mqtt.js');
        // #ifdef H5
        var client = mqtt.connect('ws://mqtt.hnbxwhy.com:8083/mqtt');
        // #endif
        // #ifdef MP-WEIXIN||APP-PLUS
        var client = mqtt.connect('wx://mqtt.hnbxwhy.com:8083/mqtt');
        // #endif
        self.mqttClient = client;
        client.on('connect', function() {
          self.connected = true;
          self.isConnecting = false;
          self.logs.push('MQTT连接成功');
          if (!self.isSubscribed) {
            client.subscribe('AppAct22279', function(err) {
              if (err) {
                self.logs.push(`订阅失败: ${err.message}`);
              } else {
                self.isSubscribed = true;
                self.logs.push('已订阅主题: AppAct22279');
              }
            });
          }
        }).on('reconnect', function() {
          self.logs.push('正在重连...');
          self.connected = false;
          self.isConnecting = true;
        }).on('error', function(error) {
          self.logs.push(`连接错误: ${error && error.message ? error.message : error}`);
          self.connected = false;
          self.isConnecting = false;
        }).on('end', function() {
          self.logs.push('连接已断开');
          self.connected = false;
          self.isConnecting = false;
          self.isSubscribed = false;
        }).on('message', function(topic, message) {
          const msgStr = message.toString();
          const messageInfo = self.parseMessage(topic, msgStr);
          const isDuplicate = self.receivedMessages.some(item => 
            item.content === messageInfo.content && item.timestamp === messageInfo.timestamp
          );
          if (!isDuplicate) {
            self.receivedMessages.unshift(messageInfo);
            self.logs.push(`收到${messageInfo.type}消息: ${messageInfo.summary}`);
          }
        });
      } catch (initError) {
        self.logs.push(`初始化错误: ${initError.message}`);
        self.isConnecting = false;
      }
    },
    // 发送消息（适配MQTT）
    sendMessage() {
      if (!this.connected) {
        uni.showToast({
          title: '未连接服务器',
          icon: 'none'
        });
        return;
      }
      if (!this.messageToSend.trim()) {
        uni.showToast({
          title: '消息内容不能为空',
          icon: 'none'
        });
        return;
      }
      const topic = 'AppAct22279';
      const message = this.messageToSend;
      this.sendMessageMQTT(topic, message);
    },
    // 使用MQTT发送消息
    sendMessageMQTT(topic, message) {
      const self = this;
      this.mqttClient.publish(topic, message, { qos: 1 }, (err) => {
        if (err) {
          self.logs.push(`发送失败: ${err.message}`);
          uni.showToast({
            title: '发送失败',
            icon: 'none'
          });
        } else {
          self.logs.push(`已发送消息到 ${topic}: ${message}`);
          uni.showToast({
            title: '发送成功',
            icon: 'success'
          });
          const messageInfo = self.parseMessage(topic, message);
          messageInfo.isSelf = true;
          const isDuplicate = self.receivedMessages.some(item => 
            item.content === messageInfo.content && item.timestamp === messageInfo.timestamp
          );
          if (!isDuplicate) {
            self.receivedMessages.unshift(messageInfo);
          }
          self.messageToSend = '';
        }
      });
    },
    // 解析消息类型（保留原有）
    parseMessage(topic, message) {
      const msgStr = message.toString();
      let messageInfo = {
        topic,
        raw: msgStr,
        timestamp: new Date().toLocaleString()
      };
      if (msgStr.startsWith('{') && msgStr.endsWith('}') ||
        msgStr.startsWith('[') && msgStr.endsWith(']')) {
        try {
          const jsonData = JSON.parse(msgStr);
          messageInfo.type = 'JSON';
          messageInfo.content = JSON.stringify(jsonData, null, 2);
          messageInfo.summary = JSON.stringify(jsonData);
        } catch (e) {
          messageInfo.type = '文本';
          messageInfo.content = msgStr;
          messageInfo.summary = msgStr.length > 30 ? msgStr.substring(0, 30) + '...' : msgStr;
        }
      } else {
        messageInfo.type = '文本';
        messageInfo.content = msgStr;
        messageInfo.summary = msgStr.length > 30 ? msgStr.substring(0, 30) + '...' : msgStr;
      }
      return messageInfo;
    },
    // 断开连接
    disconnect() {
      if (this.mqttClient) {
        this.mqttClient.end();
        this.mqttClient = null;
        this.logs.push('已主动断开MQTT连接');
      }
      this.connected = false;
      this.isConnecting = false;
      this.isSubscribed = false;
    }
  },
  beforeDestroy() {
    this.disconnect();
  }
}
</script>

<style>
.container {
  padding: 20rpx;
  height: 100vh;
  box-sizing: border-box;
}

.control-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.status {
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  background-color: #f5f5f5;
  font-size: 28rpx;
}

.send-area {
  display: flex;
  margin-bottom: 20rpx;
}

.message-input {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.title {
  font-weight: bold;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #eee;
}

.message-area,
.log-area {
  margin-bottom: 20rpx;
}

.messages,
.logs {
  height: 300rpx;
  padding: 10rpx 0;
  font-size: 28rpx;
}

.message-item,
.log-item {
  padding: 10rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.timestamp {
  color: #999;
  font-size: 24rpx;
}

.type {
  color: #007aff;
  margin: 0 10rpx;
}

.content {
  display: block;
  margin-top: 5rpx;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>